<template>
  <div class="">
    <van-skeleton title :row="10" :loading="isFirst">
      <!-- <PackBack></PackBack> -->

      <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
        <van-swipe-item>
          <img :src="shop[0]?.photo" alt="" class="shop-img"
        /></van-swipe-item>
        <van-swipe-item v-for="(item, i) in shop[0]?.qualifications" :key="i">
          <img :src="item" alt="" class="shop-img" />
        </van-swipe-item>
      </van-swipe>

      <div class="shop-info">
        <div class="info-first">
          <p>￥{{ shop[0]?.price?.toFixed(2) }}</p>
          <p>
            <van-tag type="danger" style="font-weight: 500"
              >销量:{{ shop[0]?.sales }}</van-tag
            >
          </p>
        </div>
        <div class="info-two">{{ shop[0]?.name }}</div>
        <div class="info-their">
          <van-tag plain>规格:{{ shop[0]?.specs }}</van-tag>
        </div>
        <p style="color: red" class="font_x">供应商: {{ shop[0]?.supplier }}</p>
        <div class="info-last">
          <div>剩余库存: {{ shop[0]?.inventory - shop[0]?.sales }}</div>
          <div>
            <van-tag type="primary">购物车内数量: {{ data.number }}</van-tag>
          </div>
        </div>
      </div>
      <van-action-bar>
        <van-action-bar-icon icon="home-o" text="首页" to="/" />
        <van-action-bar-icon
          icon="shop-o"
          text="购物车"
          :badge="likeShop.count"
          @click="
            () => {
              router.push('/shop/home/buy');
            }
          "
        />
        <van-action-bar-button
          type="warning"
          @click="methods.addGoodCar(shop[0])"
          text="加入购物车"
        />
        <van-action-bar-button
          type="danger"
          @click="
            () => {
              router.push('/shop/home/buy');
            }
          "
          text="立即购买"
        />
      </van-action-bar>
    </van-skeleton>
  </div>
</template>
      
      <script setup>
import { onMounted, ref, reactive, provide } from "vue";
import { getSingleGoods } from "@/api/good";
import { useRoute, useRouter } from "vue-router";
import PackBack from "@/components/PageBack.vue";
const shop = ref([]);
const isFirst = ref(true);
const { params } = useRoute();
const data = reactive({
  view: "这是商品详情页面",
  number: 0,
  mytitle: "商品详情",
});

const router = useRouter();
const shopCar = ref([]); //当前页面购物车
const ids = ref([]); //购物车所有商品id
const likeShop = ref({
  price: 0,
  count: 0,
}); //购物车总数量和价格
const parentMessage = "商品详情"; // 父组件数据
provide("mytitle", parentMessage); // 提供数据给子组件
const methods = {
  //更新页面数据
  updateData: (item) => {
    //所有缓存已有的商品的id
    const carIds = ids.value.map((d) => d.id);

    const res = shopCar.value.find((d) => d.id === params.id);
    data.number = res?.carCount;
    if (!data.number) {
      data.number = 0;
    }
    item.value.map((d, i) => {
      if (carIds.includes(d.id)) {
        const arr = ids.value.find((e) => e.id === d.id);
        d.carCount = arr.carCount;
      } else {
        d.carCount = 0;
      }
      //这个页面因为有子集所以需要改变成这个方案
      // d.goods.map((e)=>{
      //   if (carIds.includes(e.id)) {
      //   const arr = ids.value.find((f) => f.id === e.id);
      //   e.carCount = arr.carCount;
      // } else {
      //   e.carCount = 0;
      // }
      // })
    });
  },

  //更新购物车数据
  save: (shop) => {
    const result = shop.value.find((d) => d.carCount === 0);
    if (result) {
      shop.value.map((d, i) => {
        if (d.carCount === 0) {
          shop.value.splice(i, 1);
        }
      });
    }
    //存入最新数据
    localStorage.setItem("shopCar", JSON.stringify(shop.value));

    //更新数据
    shopCar.value = JSON.parse(localStorage.getItem("shopCar"));

    likeShop.value.price = 0;
    likeShop.value.count = 0;
    shopCar.value.map((d) => {
      if (d.isPromote === 1) {
        likeShop.value.price += d.promotePrice * d.carCount;
      }

      if (d.isPromote === 0) {
        likeShop.value.price += d.price * d.carCount;
      }
      likeShop.value.count += d.carCount;
    });
  },

  //购物车新增
  addGoodCar: (item) => {
    //查看购物车是否已经存在
    const result = shopCar.value.find((d) => d.id === item.id);
    if (result) {
      //已经存在，数量+1
      shopCar.value.map((d) => {
        if (item.id === d.id) {
          d.carCount += 1;

          //更新id库中的数据
          ids.value.map((e) => {
            if (e.id === d.id) {
              e.carCount += 1;
            }
          });
        }
      });
    }

    if (!result) {
      //不存在，添加进购物车
      shopCar.value.push({ ...item, carCount: 1 });
      ids.value.push({ id: item.id, carCount: 1 });
    }

    //更新存储数据
    methods.save(shopCar);
    //更新页面数据
    methods.updateData(shop);
  },

  //购物车减少
  minusGoodCar: (item) => {
    //查看购物车是否已经存在
    const result = shopCar.value.find((d) => d.id === item.id);
    if (result.carCount >= 1) {
      //已经存在，数量-1
      shopCar.value.map((d) => {
        if (item.id === d.id) {
          d.carCount -= 1;

          //更新id库中的数据
          ids.value.map((e, i) => {
            if (e.id === d.id) {
              e.carCount -= 1;
            }
          });
        }
      });
    }

    //数量为0，在购物车中清除 在ids库中清除
    if (result.carCount === 0) {
      console.log("清除ids");
      shopCar.value.map((d, i) => {
        if (item.id === d.id) {
          shopCar.value.splice(i, 1);
        }
      });
      ids.value.map((d, i) => {
        if (item.id === d.id) {
          ids.value.splice(i, 1);
        }
      });
    }

    //更新存储数据
    methods.save(shopCar);
    //更新页面数据
    methods.updateData(shop);
  },
  //获取页面单个商品数据
  getSingleGoods: () => {
    getSingleGoods({ id: params.id }).then((res) => {
      if (res.result === 0) {
        shop.value = [res.data];
        methods.updateData(shop);
        isFirst.value = false;
      }
    });
  },
};

onMounted(() => {
  //  特别注意:页面初始数据要在购买数量的处理在获取页面的方法中处理

  const shopCar_history = localStorage.getItem("shopCar");
  //符合条件即为不需要初始化购物车
  if (shopCar_history !== "" && shopCar_history !== null) {
    //不需要初始化购物车，将历史购物车赋值当前页面
    //缓存中的购物车
    const cars = JSON.parse(shopCar_history);
    cars.map((d) => {
      // 购买数量和价格处理
      if (d.isPromote === 1) {
        likeShop.value.price += d.promotePrice * d.carCount;
      }

      if (d.isPromote === 0) {
        likeShop.value.price += d.price * d.carCount;
      }
      likeShop.value.count += d.carCount;
    });

    //赋值给本地的购物车
    shopCar.value = cars;
    //赋值给本地的购物车id和数量
    ids.value = cars.map((d) => ({ id: d.id, carCount: d.carCount }));
  } else {
    //初始化购物车
    localStorage.setItem("shopCar", JSON.stringify([]));
  }

  methods.getSingleGoods();
});
</script>
  
  
  <style scoped>
.renew {
  float: right;
  height: 22px;
  width: 50px;
}

/* .shopDetailContainer {
    
  } */
.shop-img {
  width: 100%;
  height: 300px;
}

.divider {
  /* border-bottom: 1px solid #c2cbcb; */
  margin-top: 5px;
}

.shop-info {
  padding: 5px;
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
}

p {
  margin: 5px 0px 5px 0px;
}

.info-first {
  display: flex;
  justify-content: space-between;
  color: red;
  font-weight: bold;
}

.info-two {
  font-size: 13px;
  font-weight: bold;
}

.info-their {
  margin-top: 5px;
  font-size: 10px;
  /* color: #c2cbcb; */
  color: #b2b2b2;
}

.info-last {
  margin-top: 10px;
  font-size: 10px;
  /* color: #c2cbcb; */
  color: #b2b2b2;
  display: flex;
  justify-content: space-between;
}

.info-bottom {
  /* height: 80px; */
  border-bottom: 1px solid #eee;
  padding: 10px;
  box-sizing: border-box;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
}

.info-bottom-first {
  display: flex;
  justify-content: space-between;
  padding: 0px 10px 0px 10px;
  font-weight: 600;
}
</style>